package com.ruipengkj.component.jtree;

import java.util.Iterator;
import java.util.Map;

import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.tree.DefaultTreeModel;

public abstract class AbstractLoadTreeModel implements TreeExpansionListener{
	
	private JTree tree;
	private DefaultTreeModel treeModel = null;
	
	// 增加“载入中...”子结点的方法
    private void addLoadingNode(DefaultTreeModel treeModel, OverwriteDefaultMutableTreeNode parent) {
    	OverwriteDefaultMutableTreeNode loading = new OverwriteDefaultMutableTreeNode("载入中...");
        treeModel.insertNodeInto(loading, parent, parent.getChildCount());
    }

	// 从数据表中读取expandNode的子结点.返回值为处理时长
	public long asynchLoad(Map<Integer, String> map, boolean isLeaf,
			OverwriteDefaultMutableTreeNode expandNode, DefaultTreeModel treeModel) {
		long handleTime = 0L; // 本次异步加载的处理时长
		long start = System.currentTimeMillis(); // 开始处理的时刻
		try {
			if (map != null && map.size() != 0) {
				Iterator<Integer> it = map.keySet().iterator();
				while (it.hasNext()) {
					int key = it.next();
//					OverwriteDefaultMutableTreeNode obj = new OverwriteDefaultMutableTreeNode(key, map.get(key));
//					if (isLeaf) {
//						addLoadingNode(treeModel, obj);
//					}
//					treeModel.insertNodeInto(obj, expandNode, expandNode.getChildCount());
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			handleTime = System.currentTimeMillis() - start; // 计算出处理时长
		}
		return handleTime;
	}

	@Override
	public void treeExpanded(TreeExpansionEvent event) {
//		final TDeptDefaultMutableTreeNode expandNode = (TDeptDefaultMutableTreeNode) event.getPath().getLastPathComponent();
//		if (!expandNode.isVisited()) {
//			expandNode.setVisited(true); 
//			tree.setEnabled(false);
//			new SwingWorker<Long, Void>() {
//				@Override
//				protected Long doInBackground() throws Exception {
//					return asynchLoad(expandNode, treeModel);
//				}
//				@Override
//				protected void done() {
//					treeModel.removeNodeFromParent(expandNode.getFirstLeaf());
//					treeModel.nodeStructureChanged(expandNode); 
//					tree.setEnabled(true);
//				}
//			}.execute();
//		}
	}
}
